<template>
  <el-container
      v-loading="loading"
      element-loading-text="拼命生成订单中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-header style="height:120px;border-bottom: 2px solid darkorange;background-color: rgba(255,255,255,0.54)">
      <div style="width: 1200px;margin: auto;display: flex;justify-content: space-between">
        <span style="display:inline-block;font-size: 32px;font-weight: 900;line-height: 120px;">订单确认</span>
        <span style="display: inline-block;line-height: 120px;color: darkgray">{{ user.userName }}</span>
      </div>
    </el-header>
    <el-main style="background-color: rgba(153,169,191,0.18);padding: 0px">
      <div style="background-color:white;width:1200px;margin:30px auto 0;padding-top: 30px;padding-left: 30px ">
        <p style="font-size: 18px;color: darkgray">收货地址</p>
        <!--    现有的收货地址    -->
        <div style="display: flex;flex-wrap: wrap">
          <div v-for="(item, index) in tableData " :key="item.id">
            <div class="orderD"
                 style="width: 278px;height: 178px;border: 1px solid rgba(169,169,169,0.47);margin:0 15px 15px 0px;">
              <div style="padding: 20px" @click="get(item,index)">
                <p class="orderP">{{ item.addPerson }}</p>
                <p class="orderP1">{{ item.addPhone }}</p>
                <p class="orderP1">{{ item.addProvince }} {{ item.addCity }} {{ item.addDistrict }}
                  {{ item.addDetail }}</p>
                <p class="orderP1">{{ item.addStatus }}</p>
              </div>
              <div style="display: flex;justify-content: space-between">
                <el-button @click="open(item.addressId)" style="border: none;font-size: 28px" icon="el-icon-delete"
                           circle></el-button>
                <el-button @click="getAddress(index)" style="border: none;font-size: 28px" icon="el-icon-edit"
                           circle></el-button>
              </div>
            </div>
          </div>
          <div style="position: relative;width: 280px;">
            <div style="position: absolute;right: 85px;top: 30px">
              <p class="el-icon-circle-plus" style="font-size: 32px;color: rgba(169,169,169,0.47);"></p>
              <p style="position: relative;color: rgba(169,169,169,0.47);top: -40px;left: -15px;font-size: 14px">
                添加新地址</p>
            </div>
            <el-button @click="getAddress(-1)"
                       style="border: 1px solid rgba(169,169,169,0.47);border-radius:0px;width: 280px;height: 180px;"></el-button>
          </div>
        </div>

        <!--     商品   -->
        <div>
          <h3 style="margin: 40px 0 5px">商品</h3>
          <div
              style="padding: 6px 0px;width: 100%;border-top: 1px solid rgba(169,169,169,0.5);border-bottom: 1px solid rgba(169,169,169,0.5)">
            <div v-for="Item in list" style="display: flex;justify-content: space-between">
              <div style="height: 50px;width:400px;margin: 10px 0;display: flex;justify-content: space-between">
                <img style="width: 50px;display: inline-block;height: 50px"
                     :src="'data:image/jpeg;base64'+Item.productPhoto">
                <span style="display: inline-block;line-height: 50px">{{ Item.productName }}</span>
              </div>
              <div style="width: 100px;line-height: 70px"> {{ Item.productPrice }}元*{{ Item.num }}</div>
              <div style="width: 110px;line-height: 70px"> {{
                  Item.productPrice * Item.productAmount
                }}元
              </div>
            </div>
          </div>

          <div style="width:400px;height:250px;margin-top: 50px;position: relative;left:780px">
            <div style="display: flex;justify-content: space-between;color: darkgray;margin-bottom: 5px">
              <p><span class="orderSpan" style=" width: 200px;text-align:right;display:inline-block">支付方式：</span></p>
              <el-radio-group v-model="orderPayment" size="medium" @change="setMoney">
                <el-radio-button label="支付宝"></el-radio-button>
                <el-radio-button label="预存款" :disabled="isEnough"></el-radio-button>
              </el-radio-group>

            </div>
            <div style="color: darkgray;margin-bottom: 5px;text-align: right">
              <p v-if="isEnough">预存款余额不足，建议先<a @click="toBalance">充值</a>再付款哦</p>
            </div>

            <div style="display: flex;justify-content: space-between;color: darkgray;margin-bottom: 5px">
              <span class="orderSpan" style=" width: 200px;text-align:right;display:inline-block">商品件数：</span>
              <span class="orderSpan" style="display:inline-block;color:#ff6100 ">{{ num }}件</span>
            </div>
            <div style="display: flex;justify-content: space-between;color: darkgray">
              <span class="orderSpan" style=" width: 200px;text-align:right;display:inline-block">商品总价：</span>
              <span class="orderSpan" style="display:inline-block;color:#ff6100 ">{{ totalPrices }}元</span>
            </div>
            <div style="display: flex;justify-content: space-between;color: darkgray">
              <span class="orderSpan" style=" width: 200px;text-align:right;display:inline-block">会员抵扣：</span>
              <span class="orderSpan" style="display:inline-block;color:#ff6100 ">{{ discount }}元</span>
            </div>
            <div style="display: flex;justify-content: space-between;color: darkgray;margin-top: 20px">
              <span class="orderSpan" style=" width: 200px;text-align:right;display:inline-block;line-height: 50px">应付总额：</span>
              <span class="orderSpan"
                    style="display:inline-block;font-size:28px;color:#ff6100 ">{{( totalPrices - discount).toFixed(2) }}元</span>
            </div>
          </div>

          <div style="border-top:1px solid rgba(169,169,169,0.5);padding: 30px 0;">
            <div style="position: relative;left: 790px">
              <el-button @click="car"
                         style="background-color:darkgray;height: 50px;width: 200px;border-radius: 0px;font-size: 18px;font-weight: 400;color: white">
                返回
              </el-button>
              <el-button @click="pay"
                         style="background-color:#ff6100;height: 50px;width: 200px;border-radius: 0px;font-size: 18px;font-weight: 400;color: white">
                提交订单
              </el-button>
            </div>
          </div>
        </div>
      </div>

    </el-main>
    <el-footer style="background-color: rgba(153,169,191,0.18);padding: 20px"></el-footer>
  </el-container>
</template>

<script>

import {mapMutations} from 'vuex'
import router from "@/router";

export default {

  data() {
    return {
      totalPrices: '',
      num: '',
      shopObj1: '',
      addressStatusIndex: -1,
      selectedOptions: {
        value: 'name',
        label: 'name',
      },
      loading: false,
      address2: '',
      username: 'test',
      tableData: [],
      index: -1,
      address: '',
      dialogFormVisible1: false,
      dialogFormVisible: false,
      form: {
        addressUser: '',
        addressTel: '',
        addressProvince: '',
        addressCity: '',
        addressDistrict: '',
        addressDetail: '',
        addressStatus: '',
      },
      formLabelWidth: '150px',
      user: {},
      orderPayment: "预付款",
      discount: 1,
      isEnough: false,
      list: "",
      newOrderId: "",
      timer:null
    }
  },
  mounted() {
    //is user
    let jsonUser = sessionStorage.getItem("user")
    if (jsonUser == '' || null == jsonUser) {
      this.$message.warning("请先登录")
      this.$router.push("/")
    } else {
      //json String to  json object
      let jsonObj = JSON.parse(jsonUser)
      this.user = jsonObj
    }

    this.getAllAddress()
    this.getShop()
    this.getAddressStatus()
  },
  methods: {
    ...mapMutations('address', ['setaddresslist']),
    toBalance() {
      this.$router.push("deposit")
    },
    getShop() {
      let listStr = sessionStorage.getItem("data")
      this.list = JSON.parse(listStr)
      this.num = this.list.length
      let a = 0;
      for (let i = 0; i < this.list.length; i++) {
        a += (this.list[i].productPrice * this.list[i].productAmount);
      }
      this.totalPrices = a.toFixed(2)
      console.log(this.totalPrices)
    },
    async getAllAddress() {
      await this.$axios.get("api/userAddress/findAddress/" + this.user.userId).then(r => {
        // this.tableData =  r.data
        for (let a of r.data) {
          if (a.addStatus == 1) {
            a.addStatus = "非默认地址"
            this.tableData.push(a)
          } else if (a.addStatus == 0) {
            a.addStatus = "默认地址"
            this.tableData.push(a)
          }
        }
      })
    },
    setMoney() {
      if (this.orderPayment == "支付宝") {
        console.log("支付宝")
        this.discount = 0
      } else {
        this.discount = (this.totalPrices - (this.user.level * this.totalPrices / 10)).toFixed(2)
      }
    },
    car() {
      router.back()
    },
    getAddress(index) {

      if (index != -1) {
        if (this.tableData[index].address.length == 0) {
          this.tableData[index].address.push(this.tableData[index].addressProvince, this.tableData[index].addressCity, this.tableData[index].addressDistrict, this.tableData[index].addressCounty)
        }
        this.$axios.get("/api/userAddress/findById/" + this.tableData[index].addressId).then(
            res => {
              let address = res.data
              this.setaddresslist(address)
              this.$router.push("/updateGoodsAddress")
            }
        )
      } else {
        this.$router.push("addGoodsAddress")
      }

    },
    async getAddressStatus() {
      await this.$axios.get("api/User/getUserLevel/" + this.user.userId).then(
          r => {
            if (r.data != '') {
              this.user.level = r.data
              this.discount = (this.totalPrices - (r.data * this.totalPrices / 10)).toFixed(2)

            } else {
              this.discount = 0

            }
          })
      await this.$axios.get("api/User/getUserBalance/" + this.user.userId).then(r => {
        let money = this.totalPrices - this.discount
        if (r.data / 100 < money) {
          this.discount = 0
          this.getShop()
          this.isEnough = true
          this.orderPayment = "支付宝"
        }
      })

    },
    async addOrder() {
      this.loading = true
      console.log(this.list)
      let order = {}
      order.userId = this.user.userId
      if (this.orderPayment == "支付宝") {
        order.orderPayment = 1
      } else {
        order.orderPayment = 2
      }
      order.orderTotal = (this.totalPrices - this.discount).toFixed(2) * 100
      order.addressId = this.address2.addressId
      let pList = []
      for (let p of this.list) {
        let d = {}
        d.productId = p.productId
        d.orderDAmount = p.productAmount
        d.orderDMoney = p.productPrice * p.productAmount * 100
        pList.push(d)
        if (p.checked == true) {
          this.$axios.delete("/api/car/delCar/" + this.user.userId + "/" + p.productId)

        }
      }
      order.orderDetailList = pList
      let jsonObj = JSON.stringify(order)
      let fd = new FormData()
      fd.append("jsonStr", jsonObj)
      this.$axios.post("/api/order/addOrder", fd).then(
          r => {
            console.log(r.data)
            let m = order.orderTotal / 100
            if (order.orderPayment == 1) {
              this.$axios.get("/api/payMoney/" + r.data + "/" + m)
            } else {
              let fd = new FormData()
              fd.append("balanceDMoney", order.orderTotal)
              fd.append("userId", this.user.userId)
              fd.append("orderId", r.data)
              this.$axios.post("/api/pay/addBalanceDetail", fd)
            }

            this.timer = setInterval(this.orderStatus(r.data), 1000)
          })

    },
    orderStatus(orderId) {
      console.log("111")
      this.$axios.get("/api/order/getOrderStatus/"+orderId).then(
          r=> {
            console.log(r.data)
            let orderStatus=r.data
            if(orderStatus=="已完成"){
              this.$notify({
                title: '下单成功',
                message: "下单成功",
                type: 'success'
              });
              this.orderId=""
              clearInterval(this.timer)
              this.loading=false
              this.$router.push("UserOrder")
            }else if(orderStatus=="未付款"){

            }else if(orderStatus=="已付款"){
              this.$notify({
                title: '下单成功',
                message: "下单成功",
                type: 'success'
              });
              this.orderId=""
              clearInterval(this.timer)
              this.loading=false
              this.$router.push("UserOrder")
            } else if(orderStatus=="下单中"){

            }else{
              this.$notify({
                title: '下单失败',
                message: "下单失败，请重新下单,"+"原因:"+r.data,
                type: 'warning'
              });
              this.orderId=""
              clearInterval(this.timer)
              this.loading=false
            }
          }
      )
    },
    get(val, index) {
      if (this.index != -1) {
        document.getElementsByClassName("orderD")[this.index].style = "border: 1px solid rgba(169,169,169,0.47);width: 278px;height: 178px;margin:0 15px 15px 0px";
      }
      document.getElementsByClassName("orderD")[index].style = "border: 1px solid darkorange;width: 278px;height: 178px;margin:0 15px 15px 0px"
      this.index = index;
      console.log(index)
    },
    open(id) {
      this.$confirm('此操作将永久删除该地址, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delAddress(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async delAddress(id) {
      this.$axios.delete("/api/userAddress/delAddress/" + id)
      await this.getAllAddress()
    },
    pay() {
      console.log(this.tableData)
      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].addStatus == "默认地址") {
          this.address2 = this.tableData[i]
          break
        } else {
          this.address2 = ''
        }
      }
      if (this.address2 == '' && this.index == -1) {
        this.$message({
          message: '请选择收货地址',
          type: 'warning'
        });
        return
      }
      if (this.index != -1) {
        this.address2 = this.tableData[this.index]
      }
      console.log(this.address2)
      this.addOrder()
    },
  }
}
</script>

<style>
.orderP {
  margin: 0px;
  font-size: 18px;
  color: rgba(24, 27, 28, 0.56);
  margin-bottom: 10px;
}

.orderP1 {
  font-size: 14px;
  color: rgba(24, 27, 28, 0.56);
  margin: 0px;
}

.OrderForm .el-input {
  width: 300px;
}

.orderSpan {


}
</style>